// 导入db模块
const db = require("../db");
// const uuid = require("uuid");
// 生成 token 模块
const jwt = require("jsonwebtoken");
// 导入 config 文件
const config = require("../config");
// 定义SQL语句
const sql = "select * from user_info where username=? AND status=1";
// 登录处理函数
exports.login = async (req, res) => {
  const userInfo = req.body;
  try {
    const rows = await db.query(sql, [userInfo.username]);
    // 如果用户未注册
    if (!rows.length) return res.sendData({ message: "该用户尚未注册" }, 500);
    const compareResult = userInfo.password === rows[0].password;
    if (!compareResult) return res.sendData({ message: "密码不正确！" }, 500);
    const user = {
      user_id: rows[0].user_id,
      name: rows[0].name,
      username: rows[0].username,
    };
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: config.expiresIn,
    });
    // 更新 token
    await db.query("update auth_token set token=? where user_id=?", [tokenStr, rows[0].user_id]);
    delete rows[0].password;
    res.sendData({
      message: "登录成功！",
      data: {
        token: tokenStr,
        userInfo: rows[0],
      },
    });
  } catch (err) {
    res.sendData({ message: "Failed to execute query:" + err }, 500);
  }
};
// 测试接口
exports.test = async (req, res) => {
  res.sendData({ message: "no auth test api ok" });
};
